import { defineStore } from 'pinia'
import axios from 'axios'

export const useUserStore = defineStore('user', {
  state: () => {
    let token = ''
    let userInfo = {}
    try {
      token = localStorage.getItem('token') || ''
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const parsed = JSON.parse(userInfoStr)
        // 只有包含id和role才视为有效登录
        if (parsed && parsed.id && parsed.role) {
          userInfo = parsed
        } else {
          userInfo = {}
          localStorage.removeItem('userInfo')
          localStorage.removeItem('token')
          token = ''
        }
      }
    } catch (e) {
      userInfo = {}
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
      token = ''
    }
    return {
      token,
      userInfo,
      permissions: []
    }
  },
  
  getters: {
    isLoggedIn: (state) => {
      // 检查token是否存在
      if (!state.token) return false
      
      // 检查用户信息是否完整
      if (!state.userInfo || !state.userInfo.id || !state.userInfo.role) return false
      
      return true
    },
    isHR: (state) => state.userInfo?.role === 'HR_ADMIN',
    isDepartmentManager: (state) => state.userInfo?.role === 'DEPARTMENT_MANAGER',
    isEmployee: (state) => state.userInfo?.role === 'EMPLOYEE',
    username: (state) => state.userInfo?.username || '',
    userId: (state) => state.userInfo?.id || null,
    departmentId: (state) => state.userInfo?.departmentId || null
  },
  
  actions: {
    async login(credentials) {
      try {
        // 正确获取后端返回的accessToken
        const response = await axios.post('/auth/login', credentials)
        const { accessToken, userId, username, name, role } = response.data
    
        // 创建用户信息对象
        const userInfo = {
          id: userId,
          username,
          name,
          role
        }
    
        this.setToken(accessToken)
        this.setUserInfo(userInfo)
    
        return Promise.resolve({ token: accessToken, user: userInfo })
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    async getUserInfo() {
      try {
        // 检查是否有token
        if (!this.token) {
          return Promise.reject(new Error('未登录，无法获取用户信息'))
        }
        
        // 获取用户ID
        const userId = this.userInfo.id
        if (!userId) {
          return Promise.reject(new Error('用户ID不存在'))
        }
        
        // 调用后端API获取用户详细信息
        const response = await axios.get(`/users/${userId}`)
        console.log('获取到的用户详细信息:', response.data)
        
        // 更新用户信息
        this.setUserInfo(response.data)
        return Promise.resolve(response.data)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果出错，确保清理相关状态
        if (error.response && error.response.status === 401) {
          this.logout()
        }
        return Promise.reject(error)
      }
    },
    
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
      // 确保token格式正确
      axios.defaults.headers.common['Authorization'] = token.startsWith('Bearer ') ? token : `Bearer ${token}`
    },
    
    setUserInfo(user) {
      this.userInfo = user
      localStorage.setItem('userInfo', JSON.stringify(user))
    },
    
    logout() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      delete axios.defaults.headers.common['Authorization']
    }
  }
}) 